﻿#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QClipboard>
#include <QDebug>
#include <QFile>
#include <QNetworkInterface>
#include <QString>
#include <QTime>
#include <qmessagebox.h>
#include <qprocess.h>
#include <qstring.h>
#include <qstring.h>
#include <qstring.h>
#include <qstring.h>
//#include "youdoauth.h"
#include "youdoencryp.h"
#include <QtCore/QCoreApplication>
#include <QDir>
#include <QSettings>
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
     ui->setupUi(this);
     this->setWindowTitle("授权管理系统工具V1.5.0-UdoSmart");
     //固定窗体大小
     this->setMinimumSize(960,600);
     this->setMaximumSize(960,600);
     this->setStyleSheet("QMainWindow {background-color:rgb(100,149,237)}");

     QFile file(QCoreApplication::applicationDirPath()+"/setup.inx");
     if(!file.exists()){
        bool ok = file.open(QIODevice::ReadWrite | QIODevice::Text);
        if(!ok){
             QMessageBox::information(NULL, "警告", "初始化失败",QMessageBox::Yes );
        }
        QString strRand ="" ;
        for (int i = 0; i < 4; i++) {
            int n = qrand() % 10;
            strRand = strRand %   QString::number(n) ;
        }
        this->flag = strRand;
        QString cupId =  getCpuId().toLower();
        QString cupId_8 =cupId.right(2);
        QString diskNum = getDiskNum();
        QString diskNum_8 =diskNum.right(2);
        QTime time = QTime::currentTime();
        QString _time = time.toString("hh");
        QDate date = QDate::currentDate();
        QString _date = date.toString("MMdd");
        this->numbers =0;
        QString ssid = "00"%strRand%cupId_8%diskNum_8%"&"%_date%"&"%QString::number(this->lin)%"&"%_time;
        //qDebug()<<"ssid="<<ssid;
        ssid = ssid.toUtf8().toBase64();
        QString resultStr= YoudoEncryp::instance().Encrypt(ssid,"YoudoTech*#123..");
        file.write(resultStr.toUtf8());
        file.close();
        this->ui->label_5->setText("0");
     }else{
         file.open(QIODevice::ReadOnly | QIODevice::Text);
         QTextStream in(&file);
         QString line = in.readLine();
         //qDebug()<<"line="<<line;
         this->doData(line);
         file.close();
     }

     //settings = new QSettings("setting.ini",QSettings::IniFormat);
     this->on_pushButton_2_clicked();
     //settings->setValue("mainFun", 25);
     this->localMac = getHostMacAddress();
     if(this->localMac.isEmpty() || this->localMac.isNull()){
           QMessageBox::information(NULL, "警告", "此终端暂不支持本软件支持",QMessageBox::Yes );
           close();
     }
     QTime time;
     time= QTime::currentTime();
     qsrand(time.msec()+time.second()*1000);

     QString resAdb =  this->execAdbCmd("adb forward tcp:8000 tcp:7777");
     int n = 0 ;
     while(n < 5){

       if(!resAdb.isEmpty()){
          //qApp->quit();   // 或者   aApp->closeAllWindows();
          // QProcess::startDetached(qApp->applicationFilePath(), QStringList());
          this -> qtSleep(500);
          n++;
       }else{
          break;
       }

     }


     /*QString  aa = YoudoEncryp::instance().Encrypt("QProcess::startDetached(qApp->applicationFilePath(), QStringList());","123456");
     qDebug()<< aa;
     aa = YoudoEncryp::instance().deEncrypt(aa,"123456");
     qDebug()<< aa;*/
 }
void MainWindow::qtSleep(unsigned int msec){

    QTime rechTime = QTime::currentTime().addMSecs(msec);
    while(QTime::currentTime() < rechTime){
        QApplication::processEvents(QEventLoop::AllEvents,100);
    }
}
void MainWindow::connected_SLOT()
{
     qDebug()<< "链接成功:";
    connect(tcpsocket,SIGNAL(readyRead()),this,SLOT(readyRead_Slot()));//将信号连接到槽，书写比较明确
}
void MainWindow::readyRead_Slot()//定义接收信号的槽
{
    QString buf;
    buf=tcpsocket->readAll();
    qDebug()<< "收到信息:"+buf;
    //tcpsocket->write(buf.toLocal8Bit().data());

    QStringList strList = buf.split("&");
    if(strList.length() == 0){
         qDebug()<< "错误指令";
        return;
    }

    int header = strList[0].toInt();

     switch (header) {
        case 0 :
         this->imei =  strList[1];
         this->mac =  strList[3];
         this->serial =  strList[2];
         this->iccid =  strList[4];
         ui->label_imei->setText(this->imei);
         ui->label_iccid->setText(this->iccid);
         break;
     case 1 :// 解锁成功
        this->lin  = this->lin-1;
         qDebug()<<" this->lin="<< this->lin;
        this->ui->label_5->setText(QString::number(this->lin));
        //存存入文件
         QString cupId =  getCpuId().toLower();
         QString cupId_8 =cupId.right(2);
         QString diskNum = getDiskNum();
         QString diskNum_8 =diskNum.right(2);
         QTime time = QTime::currentTime();
         QString _time = time.toString("hh");
         QDate date = QDate::currentDate();
         QString _date = date.toString("MMdd");
         qDebug()<<"解锁成功 this->flag="<<this->flag;
         QString _number;
         if(this->numbers < 10 ){
             _number = "0"% QString::number(this->numbers);
         }else{
              _number = QString::number(this->numbers);
         }
         QString ssid = _number%this->flag%cupId_8%diskNum_8%"&"%_date%"&"%QString::number(this->lin)%"&"%_time;//QString::number(this->lin);

         ssid = ssid.toUtf8().toBase64();
         QString resultStr= YoudoEncryp::instance().Encrypt(ssid,"YoudoTech*#123..");

         QFile file(QCoreApplication::applicationDirPath()+"/setup.inx");
          if(!file.exists()){
             QMessageBox::information(NULL, "警告", "操作错误",QMessageBox::Yes );
          }
          bool ok = file.open(QIODevice::ReadWrite | QIODevice::Text);
          if(ok){
              file.write(resultStr.toUtf8());
              file.close();
          }else{
              QMessageBox::information(NULL, "警告", "操作错误",QMessageBox::Yes );
          }

          this->isLock = true;

      break;
     }

}
MainWindow::~MainWindow()
{
    delete ui;
    if(this->tcpsocket != nullptr){
       this->tcpsocket->close();
    }

}



QString MainWindow::execAdbCmd(const QString cmd)
{

    std::string str = cmd.toStdString();
    const char* ch = str.c_str();
    QProcess p(0);
    p.start(ch);
    p.closeWriteChannel();
    p.waitForFinished();

    QString result = QString::fromLocal8Bit(p.readAllStandardOutput());
    qDebug()<< result;
    if(result.contains("List of devices attached",Qt::CaseSensitive)){
       //this->ui->comboBox->clear();
       int position=  result.lastIndexOf("attached");
       result = result.mid(position+10,result.lastIndexOf("\r\n\r\n\r\n"));
      /* if(result.indexOf("device") ==  result.lastIndexOf("device")){
            result = result.replace(QRegExp("\\\tdevice"), "");
            result = result.replace(QRegExp("\\\r\n"), "");
            this->ui->comboBox->addItem(result);
            this->deviceObjStr = result;
            return  result;
       }
       //多个devices 做处理
       result = result.replace(QRegExp("\\\r\n"), "");
       this->deviceList.clear();
       this->deviceList =  result.split("\tdevice");
       qDebug() << this->deviceList.size()  << endl;
       this->ui->logText->append("检测到设备数量:"+QString::number((this->deviceList.size() -1 )));
       for (int i = 0; i < this->deviceList.size()-1; ++i)
       {
            if(i==0){
                 this->deviceObjStr = this->deviceList.at(i);
            }
            this->ui->logText->append("设备:"+this->deviceList.at(i));
            this->ui->comboBox->addItem(this->deviceList.at(i));
       }*/
       qDebug()<< result;
       return  "";
    }else if(result.contains("Broadcast completed: result=0")){
       return  "ok";
    }else if(result.contains("not found")){
        QMessageBox::information(NULL, "写入错误", "USB已拔出，请重新读取设备",QMessageBox::Yes );
        //return  "";
         return "未找到设备，请重新读取设备";
    }else if(result.contains("more than one device/emulator")){
        QMessageBox::information(NULL, "操作失败", "请选择设备",QMessageBox::Yes );
       // return  "";
        return "检测到有多个设备插入";
    }else{
       // return "-1";
        return  result;
    }

}

void MainWindow::on_pushButton_2_clicked()
{
    this->isLock = false;
    this->ui->label_iccid->setText("");
    this->ui->label_imei->setText("");
    this->execAdbCmd("adb forward tcp:8000 tcp:7777");
    tcpsocket=new QTcpSocket(this);
    tcpsocket->connectToHost("127.0.0.1",8000);//转为无符号，连接服务器端口
    connect(tcpsocket,SIGNAL(connected()),this,SLOT(connected_SLOT()));

}

void MainWindow::on_pushButton_clicked()
{
  if(this->lin <= 0){
      QMessageBox::information(NULL, "提示", "授权码不足!",QMessageBox::Yes );
      return;
  }
  if(this->isLock){
      QMessageBox::information(NULL, "提示", "设备已解锁，设备链接USB执行请刷新!",QMessageBox::Yes );
      return;
  }
  QString msg = "lock";
  QTime time = QTime::currentTime();
  QString _time = time.toString("mm");
  QString head = "L"%QString::number( _time.toInt()+11)%this->imei.right(5)%this->serial.right(2)%"K";
  head = head.toUtf8().toBase64();
  this->tcpsocket->write(head.toLocal8Bit().data());
}

QString MainWindow::getHostMacAddress()
{
        QList<QNetworkInterface> nets = QNetworkInterface::allInterfaces();// 获取所有网络接口列表
        int nCnt = nets.count();
        //qDebug()<<nets;
        QString strMacAddr = "";
        for(int i = 0; i < nCnt; i ++)
        {
            // 如果此网络接口被激活并且正在运行并且不是回环地址，且该mac的ip地址不能是回环地址并且是ipv4地址，则就是我们需要找的Mac地址
            if(nets[i].flags().testFlag(QNetworkInterface::IsUp) &&
               nets[i].flags().testFlag(QNetworkInterface::IsRunning)
               && !nets[i].flags().testFlag(QNetworkInterface::IsLoopBack))
            {
                for (int j=0;j<nets[i].addressEntries().size() ;j++ ) {
                //该mac的ip地址不能为172.0.0.1，且需是ipv4地址
                if(nets[i].addressEntries().at(j).ip()!=QHostAddress::LocalHost&&nets[i].addressEntries().at(j).ip().protocol()== QAbstractSocket::IPv4Protocol
){
                        strMacAddr = nets[i].hardwareAddress();
                    }
                }
            }
        }
        return strMacAddr;
}

QString MainWindow::getWMIC(const QString &cmd)
{
    //获取cpu名称：wmic cpu get Name
    //获取cpu核心数：wmic cpu get NumberOfCores
    //获取cpu线程数：wmic cpu get NumberOfLogicalProcessors
    //查询cpu序列号：wmic cpu get processorid
    //查询主板序列号：wmic baseboard get serialnumber
    //查询BIOS序列号：wmic bios get serialnumber
    //查看硬盘：wmic diskdrive get serialnumber
    QProcess p;
    p.start(cmd);
    p.waitForFinished();
    QString result = QString::fromLocal8Bit(p.readAllStandardOutput());
    QStringList list = cmd.split(" ");
    result = result.remove(list.last(), Qt::CaseInsensitive);
    result = result.replace("", "");
    result = result.replace("", "");
    result = result.simplified();
    return result;
}
QString MainWindow::getCpuName()
{
    return getWMIC("wmic cpu get name");
}

QString MainWindow::getCpuId()
{
    return getWMIC("wmic cpu get processorid");
}
QString MainWindow::getBaseboardId()
{
    return getWMIC("wmic bios get serialnumber");
}
QString MainWindow::getDiskNum()
{
    return getWMIC("wmic diskdrive where index=0 get serialnumber");
}
QString MainWindow::ByteArrayToHexString(QByteArray data){
    QString ret(data.toHex().toUpper());
    int len = ret.length()/2;
    //qDebug()<<len;
    for(int i=1;i<len;i++)
    {
        //qDebug()<<i;
        ret.insert(2*i+i-1,"");
    }

    return ret;
}
void MainWindow::doData(QString aa)
{
    QString resultStr = YoudoEncryp::instance().deEncrypt(aa,"YoudoTech*#123..");
    QString addLin = QByteArray::fromBase64(resultStr.toUtf8());

    QStringList qList = addLin.split("&");
    if(qList.length() != 4){
       QMessageBox::information(NULL, "提示", "系统错误1!",QMessageBox::Yes );
       return;
    }
    QString cupId =  getCpuId().toLower();
    QString cupId_8 =cupId.right(2);
    QString diskNum = getDiskNum();
    QString diskNum_8 =cupId_8 % diskNum.right(2);
    QString serial = qList[0].mid(0,2);
    this->numbers=serial.toInt();
    QString last = qList[0].mid(2,4);
    this->flag = last;

    QString foot = qList[0].mid(6,10);
    //qDebug()<<"doData >> last"<<last  <<"   addLin->"<<addLin << "  foot->"<<foot;
    if(foot != diskNum_8){
        QMessageBox::information(NULL, "提示", "系统错误2!",QMessageBox::Yes );
        return;
    }

    this->lin =  qList[2].toInt();
    this->ui->label_5->setText(qList[2]);
}
void MainWindow::on_pushButton_3_clicked()
{
    //增加授权码
    QString lineStr = this->ui->lineEdit->text();
    if(lineStr.isEmpty()){
        QMessageBox::information(NULL, "提示", "授权码不能为空!",QMessageBox::Yes );
        return;
    }
    if(lineStr.length() <  20){
        QMessageBox::information(NULL, "提示", "请输入正确的授权码0x99!",QMessageBox::Yes );
        return;
    }
    QString resultStr = YoudoEncryp::instance().deEncrypt(lineStr,"YoudoTech*#123..");
    QString addLin = QByteArray::fromBase64(resultStr.toUtf8());
    qDebug()<<"addLin->"<<addLin;
    QStringList qList = addLin.split("&");
    if(qList.length() != 4){
       QMessageBox::information(NULL, "提示", "请输入正确的授权码0x50!",QMessageBox::Yes );
       return;
    }
    QString cupId =  getCpuId().toLower();
    QString cupId_8 =cupId.right(2);
    QString diskNum = getDiskNum();
    QString diskNum_8 =cupId_8 % diskNum.right(2);
    QString serial = qList[0].mid(0,2);
    int _number = serial.toInt();
   // qDebug()<<"numbers:"<<numbers << "_number:" <<_number << " serial->"<<serial;
    if(_number-1 != this->numbers){
        //如果序列不是+1 则是非法授权码
        QMessageBox::information(NULL, "提示", "请输入正确的授权码0x90!",QMessageBox::Yes );
        return;
    }

    QString last = qList[0].mid(2,4);
    QString foot = qList[0].mid(6,10);

    //qDebug()<<"增加的last="<<last<<" 增加授权码原来 this->flag ="<<this->flag ;
    if(last.compare(this->flag) == 0){
        QMessageBox::information(NULL, "提示", "请输入正确的授权码0x69!",QMessageBox::Yes );
        return;
    }


    QDate date = QDate::currentDate();
    QString _date = date.toString("MMdd");
    if(foot != diskNum_8){
        QMessageBox::information(NULL, "提示", "请输入正确的授权码0x53!",QMessageBox::Yes );
        return;
    }
    if(qList[1] != _date){
        QMessageBox::information(NULL, "提示", "请输入正确的授权码0x54!",QMessageBox::Yes );
        return;
    }

     QFile file(QCoreApplication::applicationDirPath()+"/setup.inx");
    if(!file.exists()){
       QMessageBox::information(NULL, "警告", "操作错误",QMessageBox::Yes );
    }
    bool ok = file.open(QIODevice::ReadWrite | QIODevice::Text);
    if(ok){
        //增加授权数
        int total = this->lin +  qList[2].toInt();
        lineStr = qList[0]%"&"%qList[1]%"&"%QString::number(total)%"&"%qList[3];
        lineStr = lineStr.toUtf8().toBase64();
        QString resultStr= YoudoEncryp::instance().Encrypt(lineStr,"YoudoTech*#123..");
        //qDebug()<<"lineStr="<<lineStr;
        file.write(resultStr.toUtf8());
        file.close();
        //重新初始化数据
        this->flag = last;
        this->lin  = total;
        this->ui->label_5->setText(QString::number( this->lin));
        this->ui->lineEdit->setText("");
        this->numbers = _number;
    }else{
        QMessageBox::information(NULL, "警告", "操作错误",QMessageBox::Yes );
    }



}
//EdthrawxYMyIdiPt7ihb3wyu2w0pu1TeqQKS9sPyZSI
void MainWindow::on_copt_btn_clicked()
{

   QString cupId =  getCpuId().toLower();
   QString cupId_8 =cupId.right(2);
   QString diskNum = getDiskNum();
   QString diskNum_8 =diskNum.right(2);

   QTime time = QTime::currentTime();
   QString _time = time.toString("hh");

    QDate date = QDate::currentDate();
    QString _date = date.toString("MMdd");
    QString numserInt ;
    if(this->numbers < 10){
        numserInt = "0" % QString::number(this->numbers);
    }else{
        numserInt = QString::number(this->numbers);
    }
    QString ssid =
       numserInt%this->flag%cupId_8%diskNum_8%"&"%_date%"&"%QString::number(this->lin)%"&"%_time;
    //qDebug()<<"组装:"<<ssid <<"   this->flag->"<<this->flag;
    ssid = ssid.toUtf8().toBase64();

    QString resultStr= YoudoEncryp::instance().Encrypt(ssid,"YoudoTech*#123..");
    //qDebug()<<resultStr;
    QClipboard *pClip = QApplication::clipboard();
    pClip->setText(resultStr.left(resultStr.length()-1));
    QMessageBox::information(NULL, "提示", "复制成功，请将序列号码发送给厂商!",QMessageBox::Yes );

    //解密
   /* resultStr = YoudoEncryp::instance().deEncrypt(resultStr,"youdotech*#123..");
    qDebug()<<"deEncrypt:"<<resultStr;
    //qDebug()<<"deEncrypt:"<<resultStr;
    qDebug()<< "fromBase64->" <<QByteArray::fromBase64(resultStr.toUtf8());*/
    //复制序列码
   /* cupId  = "youdotech";
     QVector<QString>_generateKey(2);
     _generateKey[0]  = "33467408261828326873$6,18,11,4,2,13"; //this->generateKey();
     //qDebug()<<"---aaa[0]----" << aaa[0];
     QString _rawKey = getRawKeyByP(_generateKey[0]);
     //qDebug()<<"---_rawKey----" << _rawKey;
     QString data = des(_rawKey ,cupId ,true, false,"");
     qDebug()<<"---data----" << data;
     QByteArray ba = QByteArray::fromHex(data.toUtf8()).toHex();
     _generateKey[1] =   ByteArrayToHexString(ba);
     qDebug()<<"---aaa[1]----" << _generateKey[1];*/
}

/**
 * 生成P信息
 */
 QString MainWindow::generateKey() {

       QString strRand ;
       for (int i = 0; i < 20; i++) {
           int n = qrand() % 10;
           strRand = strRand %   QString::number(n) ;
       }
       QString strRand1;
       for (int i = 0; i < 6; i++) {
           int n = qrand() % 20;
           strRand1= strRand1 %   QString::number(n) % ",";
       }
       QStringRef el(&strRand1,0 ,  strRand1.length()-1);
       QString res = strRand % "$" %  el ;
       return res;
   }



